/**
 * WebSocket消息同步测试脚本
 * 用于验证聊天消息通过WebSocket的实时同步功能
 */

const testWebSocketSync = async () => {
  console.log('🧪 开始测试WebSocket消息同步功能...')
  
  try {
    const socket = require('socket.io-client')
    
    // 测试配置
    const testConfig = {
      serverUrl: 'http://localhost:3000',
      testUserId: 'test_user_123',
      testChatId: 'test_chat_456',
      testPeerId: 'test_peer_789'
    }
    
    console.log('📋 测试配置:', testConfig)
    
    // 创建Socket连接
    console.log('1. 创建WebSocket连接...')
    const client = socket(testConfig.serverUrl, {
      transports: ['websocket'],
      query: { userId: testConfig.testUserId }
    })
    
    // 连接成功处理
    client.on('connect', () => {
      console.log('✅ WebSocket连接成功')
      
      // 加入聊天房间
      console.log('2. 加入聊天房间...')
      client.emit('chat:join', testConfig.testChatId)
      
      // 测试消息接收
      console.log('3. 测试消息接收...')
      client.on('chat:newMessage', (payload) => {
        console.log('📨 收到新消息:', {
          chatId: payload.chatId,
          messageId: payload.message._id,
          senderId: payload.message.senderId,
          content: payload.message.content,
          type: payload.message.type,
          createdAt: payload.message.createdAt
        })
        
        // 验证消息格式
        if (payload && payload.chatId && payload.message) {
          console.log('✅ 消息格式正确')
          
          // 验证消息去重逻辑
          const messageId = payload.message._id
          if (messageId) {
            console.log('✅ 消息有唯一ID，支持去重')
          } else {
            console.log('⚠️ 消息无ID，使用组合键去重')
          }
        } else {
          console.log('❌ 消息格式错误')
        }
      })
      
      // 测试输入状态同步
      console.log('4. 测试输入状态同步...')
      client.on('chat:typing', (payload) => {
        console.log('⌨️ 收到输入状态:', {
          chatId: payload.chatId,
          userId: payload.userId
        })
      })
      
      // 测试已读状态同步
      console.log('5. 测试已读状态同步...')
      client.on('chat:readAll', (payload) => {
        console.log('👁️ 收到已读状态:', {
          chatId: payload.chatId,
          userId: payload.userId
        })
      })
      
      // 测试在线状态同步
      console.log('6. 测试在线状态同步...')
      client.on('presence:online', (payload) => {
        console.log('🟢 用户上线:', payload.userId)
      })
      
      client.on('presence:offline', (payload) => {
        console.log('🔴 用户下线:', payload.userId)
      })
      
      // 模拟发送消息
      setTimeout(() => {
        console.log('7. 模拟发送消息...')
        client.emit('chat:typing', { chatId: testConfig.testChatId })
        
        // 模拟新消息推送
        setTimeout(() => {
          const mockMessage = {
            chatId: testConfig.testChatId,
            message: {
              _id: 'msg_' + Date.now(),
              senderId: testConfig.testPeerId,
              content: '这是一条测试消息',
              type: 'text',
              createdAt: new Date().toISOString(),
              readBy: [testConfig.testPeerId]
            }
          }
          
          // 模拟服务器推送消息
          client.emit('chat:newMessage', mockMessage)
          console.log('📤 模拟消息已发送')
        }, 1000)
      }, 2000)
      
      // 测试断线重连
      setTimeout(() => {
        console.log('8. 测试断线重连...')
        client.disconnect()
        
        setTimeout(() => {
          console.log('🔄 重新连接...')
          client.connect()
        }, 2000)
      }, 5000)
      
      // 清理测试
      setTimeout(() => {
        console.log('9. 清理测试...')
        client.disconnect()
        console.log('✅ WebSocket消息同步测试完成')
      }, 8000)
    })
    
    // 连接错误处理
    client.on('connect_error', (error) => {
      console.error('❌ WebSocket连接失败:', error)
    })
    
    // 断开连接处理
    client.on('disconnect', (reason) => {
      console.log('🔌 WebSocket断开连接:', reason)
    })
    
  } catch (error) {
    console.error('❌ 测试失败:', error)
  }
}

// 模拟消息去重逻辑
const simulateMessageDeduplication = () => {
  console.log('🧪 模拟消息去重逻辑...')
  
  const messages = []
  
  const pushUniqueMessage = (newMessage) => {
    if (!newMessage) {
      console.warn('收到空消息，跳过')
      return
    }
    
    console.log('收到新消息:', {
      id: newMessage._id,
      senderId: newMessage.senderId,
      content: newMessage.content,
      type: newMessage.type,
      createdAt: newMessage.createdAt
    })
    
    const id = String(newMessage._id || '')
    
    // 如果有ID，直接按ID去重
    if (id) {
      const exists = messages.some(x => String(x._id || '') === id)
      if (exists) {
        console.log('消息已存在，跳过:', id)
        return
      }
      console.log('添加新消息:', id)
      messages.push(newMessage)
    } else {
      // 如果没有ID，使用组合键去重
      const key = `${newMessage.senderId}|${newMessage.type || 'text'}|${newMessage.content || newMessage.imageUrl || newMessage.voiceUrl || ''}|${newMessage.createdAt}`
      const exists = messages.some(x => {
        const xKey = `${x.senderId}|${x.type || 'text'}|${x.content || x.imageUrl || x.voiceUrl || ''}|${x.createdAt}`
        return xKey === key
      })
      
      if (exists) {
        console.log('消息已存在（组合键），跳过:', key)
        return
      }
      
      console.log('添加新消息（组合键）:', key)
      messages.push(newMessage)
    }
    
    console.log('当前消息数量:', messages.length)
  }
  
  // 测试消息去重
  const testMessages = [
    {
      _id: 'msg_1',
      senderId: 'user_1',
      content: '第一条消息',
      type: 'text',
      createdAt: new Date().toISOString()
    },
    {
      _id: 'msg_2',
      senderId: 'user_2',
      content: '第二条消息',
      type: 'text',
      createdAt: new Date().toISOString()
    },
    {
      _id: 'msg_1', // 重复ID
      senderId: 'user_1',
      content: '重复消息',
      type: 'text',
      createdAt: new Date().toISOString()
    },
    {
      // 无ID的消息
      senderId: 'user_3',
      content: '无ID消息',
      type: 'text',
      createdAt: new Date().toISOString()
    },
    {
      // 重复的无ID消息
      senderId: 'user_3',
      content: '无ID消息',
      type: 'text',
      createdAt: new Date().toISOString()
    }
  ]
  
  console.log('测试消息去重...')
  testMessages.forEach((msg, index) => {
    console.log(`\n测试消息 ${index + 1}:`)
    pushUniqueMessage(msg)
  })
  
  console.log('\n最终消息列表:')
  messages.forEach((msg, index) => {
    console.log(`${index + 1}. [${msg._id || 'no-id'}] ${msg.content}`)
  })
}

// 模拟WebSocket连接状态管理
const simulateConnectionManagement = () => {
  console.log('🧪 模拟WebSocket连接状态管理...')
  
  let socketConnected = false
  let autoRefreshEnabled = true
  let refreshInterval = 30000
  
  const updateConnectionStatus = (connected) => {
    socketConnected = connected
    console.log(`🔗 Socket连接状态: ${connected ? '已连接' : '已断开'}`)
    
    if (connected) {
      console.log('✅ Socket已连接，依赖实时推送，跳过自动刷新')
    } else {
      console.log('🔄 Socket未连接，启用自动刷新作为备用')
    }
  }
  
  const shouldAutoRefresh = () => {
    if (!autoRefreshEnabled) {
      console.log('⏭️ 自动刷新已禁用')
      return false
    }
    
    if (socketConnected) {
      console.log('⏭️ Socket已连接，跳过自动刷新')
      return false
    }
    
    console.log('🔄 执行自动刷新')
    return true
  }
  
  // 模拟不同场景
  console.log('场景1: Socket连接成功')
  updateConnectionStatus(true)
  shouldAutoRefresh()
  
  console.log('\n场景2: Socket断开连接')
  updateConnectionStatus(false)
  shouldAutoRefresh()
  
  console.log('\n场景3: 关闭自动刷新')
  autoRefreshEnabled = false
  shouldAutoRefresh()
  
  console.log('\n场景4: 重新开启自动刷新')
  autoRefreshEnabled = true
  shouldAutoRefresh()
}

// 运行测试
if (require.main === module) {
  testWebSocketSync()
  simulateMessageDeduplication()
  simulateConnectionManagement()
}

module.exports = { 
  testWebSocketSync, 
  simulateMessageDeduplication, 
  simulateConnectionManagement 
}
